package com.stx.bms.dao;

import com.stx.bms.entity.User;
import com.stx.bms.util.JDBCUtil;

import java.sql.*;

public class UserDAOImpl implements UserDAO {

    public User login(String username, String password){

        String sql = "select * from t_bms_user where username=? and password=?";

        Connection con = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try {
            con = JDBCUtil.getCon();

            st = con.prepareStatement(sql);
            st.setString(1, username);
            st.setString(2, password);
            rs = st.executeQuery();

            if(rs.next()){
                User user = new User();
                user.setId( rs.getInt("id") );
                user.setUsername( rs.getString("username") );
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBCUtil.close(con, st, rs);
        }
        return null;
    }

    @Override
    public boolean checkUsername(String username) {

        String sql = "select * from t_bms_user where username = ?";

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try{
            con = JDBCUtil.getCon();
            ps = con.prepareStatement(sql);
            ps.setString(1, username);
            rs = ps.executeQuery();

            if(rs.next()){
                return true;
            }

        }catch(Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.close(con, ps, rs);
        }
        return false;
    }

}
